import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {MockConfigItem} from '../../entity/mock-config-item';
import {DocService} from '../../service/doc.service';
import {Entity} from '../../entity/entity';
import {deepCopy} from '../../utils/entity-utils';
import {MockUtils} from '../../utils/mock-utils';

@Component({
    selector: 'app-doc-mock-item-config',
    templateUrl: './doc-mock-item-config.component.html',
    styleUrls: ['./doc-mock-item-config.component.css']
})
export class DocMockItemConfigComponent implements OnInit {
    /**
     * 需要被获取到焦点的元素
     */
    @ViewChild('focusInput')
    startInputElementRef: ElementRef;

    @ViewChild('randomListItemEditor')
    itemValueElementRef: ElementRef;

    private _mockConfigItem: MockConfigItem;

    itemValue: string;

    /**
     * 正在编辑的配置
     */
    item: MockConfigItem;

    editRandomListIndex = -1;

    entity: Entity;

    private _listBatchEditor: string;

    mapKey: string;

    constructor(private docService: DocService) {
    }

    ngOnInit() {
    }

    /**
     * 保存当前编辑
     */
    save() {
        // 检查输入是否合法
        if (!MockUtils.checkValue(this.item, this.mapKey)) {
            // 检查不合法
            return;
        }

        this.item.edit = false;
        Object.keys(this.item).forEach(k => {
            this._mockConfigItem[k] = this.item[k];
        });
    }

    cancel() {
        this._mockConfigItem.edit = false;
    }

    private init() {
        const entityName = this.item.entityName;
        this.entity = this.docService.getEntity(entityName);
    }

    @Input()
    set mockConfigItem(item: MockConfigItem) {
        this._mockConfigItem = item;
        // 复制一个复本，用于编辑，保存时才真正应用上
        this.item = deepCopy(item);
        this.init();
        this.focus();
    }

    get listBatchEditor(): string {
        if (!this.item.mockValueRandomList) {
            return '';
        }
        return this.item.mockValueRandomList.join('\n');
    }

    set listBatchEditor(value: string) {
        this._listBatchEditor = value;
        this.item.mockValueRandomList = this._listBatchEditor.split('\n');
    }

    checkRangeNumberInput(startInput: HTMLInputElement, endInput: HTMLInputElement) {
        if (startInput.value && parseInt(startInput.value, 10) > 0) {
            endInput.focus();
        } else {
            startInput.focus();
            return;
        }
        if (endInput.value && parseInt(endInput.value, 10) > 0) {
            // 提交
            this.save();
        } else {
            endInput.focus();
        }
    }

    checkRangeStringInput(startInput: HTMLInputElement) {
        if (startInput.value && startInput.value.length > 0) {
            this.save();
        }
    }

    /**
     * 改变mockType值时检查是否需要获取焦点
     */
    focus() {
        setTimeout(() => {
            if (this.startInputElementRef) {
                this.startInputElementRef.nativeElement.focus();
            }
        }, 0);
    }

    addItem() {
        this.item.mockValueRandomList.push('');
        this.editItem(this.item.mockValueRandomList.length - 1);
    }

    deleteItem(index: number) {
        const list = this.item.mockValueRandomList;
        list.splice(index, 1);
        if (list.length === 0) {
            list.push('');
        }
        this.editRandomListIndex = -1;
    }

    editItem(index: number) {
        this.editRandomListIndex = index;
        this.itemValue = this.item.mockValueRandomList[index];
        setTimeout(() => {
            if (this.itemValueElementRef) {
                this.itemValueElementRef.nativeElement.focus();
            }
        }, 10);
    }

    saveItem() {
        this.item.mockValueRandomList[this.editRandomListIndex] = this.itemValue;
        this.editRandomListIndex = -1;
    }

    cancelItem() {
        this.itemValue = null;
        this.editRandomListIndex = -1;
    }

    listLoopStructCreate() {
        this.checkListItem();
    }

    checkListItem() {
        // 需要循环次数
        const loopCount = this.item.mockValueStart;

        if (this.item.mockListLoopStructCreated) {
            if (this.item.children.length > loopCount) {
                // 已经超过
                this.item.children.splice(loopCount, this.item.children.length - loopCount);
                this._mockConfigItem.children.splice(loopCount, this._mockConfigItem.children.length - loopCount);
            } else {
                for (let i = this._mockConfigItem.children.length; i < loopCount; i++) {
                    const newItem = deepCopy(this._mockConfigItem.children[0]);
                    this.item.children.push(newItem);
                    this._mockConfigItem.children.push(newItem);
                }
            }
        } else {
            // 不需要预先构建结构时，只保留一个记录
            if (this._mockConfigItem.children.length > 1) {
                this.item.children.splice(1, this.item.children.length - 1);
                this._mockConfigItem.children.splice(1, this._mockConfigItem.children.length - 1);
            }
        }
    }
}
